package com.example.administrator.taxicar.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.taxicar.R;
import com.example.administrator.taxicar.utils.Constants;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class LoginActivity extends Activity implements View.OnClickListener {
    private int i = 60;
    // 手机号输入框
    private EditText inputPhoneEt;
    // 验证码输入框
    private EditText inputCodeEt;
    // 获取验证码按钮
    private Button requestCodeBtn;
    //登录的电话号
    private String phoneNums;
    //验证码
    private String CommitNum;

    // 注册按钮
    private Button commitBtn;
    private ImageView back;
    private SweetAlertDialog pDialog;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                requestCodeBtn.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                requestCodeBtn.setText("获取验证码");
                requestCodeBtn.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                // 提交验证码成功 关闭dialog 保存号码 返回MainActivity
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        pDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();
                        SharedPreferences mySharedPreferences = getSharedPreferences(Constants.LOGIN, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = mySharedPreferences.edit();
                        editor.putString(Constants.USER_LOGIN, phoneNums);
                        editor.commit();
                        finish();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }else{
                    if(event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
    /**
     * 判断一个字符串的位数
     *
     * @param str
     * @param length
     * @return
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		 */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //声明使用自定义标题
        setContentView(R.layout.activity_login);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.login_titlebar_layout);//自定义布局赋

        init();
    }
    /**
     * 初始化控件
     */
    private void init() {
        inputPhoneEt = (EditText) findViewById(R.id.driver_phone);
        inputCodeEt = (EditText) findViewById(R.id.driver_pwd);
        requestCodeBtn = (Button) findViewById(R.id.get_ms);
        commitBtn = (Button) findViewById(R.id.login);
        back = (ImageView) findViewById(R.id.title_left_img);
        requestCodeBtn.setOnClickListener(this);
        commitBtn.setOnClickListener(this);
        back.setOnClickListener(this);

        SharedPreferences sharedPreferences= getSharedPreferences(Constants.LOGIN, Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString(Constants.USER_LOGIN,"");
        if(!phone.equals("请登录")){
            inputPhoneEt.setText(phone);
        }

        // 启动短信验证sdk
        SMSSDK.initSDK(this, "12632f8e90168", "181c9671227beb04b17ab50ddf85934b");
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    @Override
    public void onClick(View v) {
        phoneNums = inputPhoneEt.getText().toString();
        CommitNum = inputCodeEt.getText().toString();
        switch (v.getId()) {
            case R.id.get_ms:
                // 1. 通过规则判断手机号
                if (!judgePhoneNums(phoneNums)) {
                    return;
                }
                // 2. 通过sdk发送短信验证
                SMSSDK.getVerificationCode("86", phoneNums);
                // 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
                requestCodeBtn.setClickable(false);
                requestCodeBtn.setText("重新发送(" + i + ")");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);
                    }
                }).start();
                break;

            case R.id.login:
                if (!judgePhoneNums(phoneNums)) {
                    return;
                }
                if(CommitNum.length()==4){
                    createProgressBar();
                    SMSSDK.submitVerificationCode("86", phoneNums, CommitNum);
                }else{
                    Toast.makeText(getApplicationContext(), "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.title_left_img:
                finish();
                break;
        }
    }

    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11) && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * progressbar
     */
    private void createProgressBar() {
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE) .setTitleText("正在加载数据");
        pDialog.show();
        pDialog.setCancelable(false);
        new CountDownTimer(800 * 5, 800) {
            public void onTick(long millisUntilFinished) {
                pDialog.getProgressHelper().setBarColor(Color.parseColor("#0392ff"));
            }
            public void onFinish() {
                pDialog.dismiss();
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }

}
